package cn.edu.cdp.jxgl_springboot_web.controller;

import cn.edu.cdp.jxgl_springboot_web.dao.AccountDao;
import cn.edu.cdp.jxgl_springboot_web.domain.Account;
import cn.edu.cdp.jxgl_springboot_web.domain.Result;
import cn.edu.cdp.jxgl_springboot_web.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {
    private final AccountDao accountDao;

    @Autowired
    public LoginController(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @PostMapping("/login")
    public Result login(String username, String password) {
        Account loginAccount = accountDao.login(username, password);

        if (loginAccount != null && loginAccount.getRole().equals("管理员")) {
            Map<String, Object> headers = new HashMap<>();
            headers.put("username", loginAccount.getUsername());
            headers.put("role", loginAccount.getRole());

            // 生成 JWT 令牌
            return Result.success(JwtUtil.generateJwt(headers));
        }
        return Result.error("用户名或密码错误");
    }
}
